// ignore_for_file: use_build_context_synchronously

import 'dart:io';
import 'package:aitao_flutter/res/r.dart';
import 'package:aitao_flutter/utils/oss_utils.dart';
import 'package:aitao_flutter/utils/sp_utils.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:nine_grid_view/nine_grid_view.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import '../../common_ui/back_nav.dart';
import '../common_ui/input_textview.dart';
import '../request/api.dart';
import '../request/requestManager.dart';
import '../style/color_style.dart';

class SendDynamicPage extends StatefulWidget {
  const SendDynamicPage({Key? key}) : super(key: key);

  @override
  State<SendDynamicPage> createState() => _SendDynamicPageState();
}

class _SendDynamicPageState extends State<SendDynamicPage> {
  List<ImageBean> _imageList = [];
  List<String> imgUrlList = [];
  List<File> imageFiles = [];
  String dynamicContent = '';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ColorStyle.backGroundColor,
      appBar: BackNavigation(
        title: '发布动态',
        rightTitle: '发布',
        rightTitleColor: ColorStyle.mainColor,
        rightBtnCallBack: () {
          sendCirclData();
        },
      ),
      body: Container(
        // margin: EdgeInsets.only(top: 6.h),
        color: Colors.white,
        child: ListView(
          children: <Widget>[
            dynamicContentWidget(),
            DragSortView(
              _imageList,
              space: 5,
              margin: const EdgeInsets.all(20),
              padding: const EdgeInsets.all(0),
              itemBuilder: (BuildContext context, int index) {
                if (imgUrlList.isEmpty) {
                  ImageBean bean = _imageList[index];
                  return PictureUtils.getWidget(bean.thumbPath!);
                }
                return CachedNetworkImage(
                    imageUrl: SpUtil.getImageUrl(imgUrlList[index]));
              },
              initBuilder: (BuildContext context) {
                return InkWell(
                  onTap: () {
                    checkPermission(context);
                  },
                  child: Container(
                    color: const Color(0xFFF0F0F0),
                    child: const Center(
                      child: Icon(
                        Icons.add,
                        size: 36,
                      ),
                    ),
                  ),
                );
              },
              // onDragListener: (MotionEvent event, double itemWidth) {
              //   switch (event.action) {
              //     case MotionEvent.actionDown:
              //       moveAction = event.action!;
              //       setState(() {});
              //       break;
              //     case MotionEvent.actionMove:
              //       double x = event.globalX! + itemWidth;
              //       double y = event.globalY! + itemWidth;
              //       double maxX = MediaQuery.of(context).size.width - 1 * 100;
              //       double maxY = MediaQuery.of(context).size.height - 1 * 100;
              //       print('Sky24n maxX: $maxX, maxY: $maxY, x: $x, y: $y');
              //       if (_canDelete && (x < maxX || y < maxY)) {
              //         setState(() {
              //           _canDelete = false;
              //         });
              //       } else if (!_canDelete && x > maxX && y > maxY) {
              //         setState(() {
              //           _canDelete = true;
              //         });
              //       }
              //       break;
              //       case MotionEvent.actionUp:
              //       moveAction = event.action!;
              //       if (_canDelete) {
              //         setState(() {
              //           _canDelete = false;
              //         });
              //         return true;
              //       } else {
              //         setState(() {});
              //       }
              //       break;
              //   }
              //   return false;
              // },
            ),
          ],
        ),
      ),
    );
  }

  Widget dynamicContentWidget() {
    return InputTextView(
      backGroundColor: ColorStyle.whiteColor,
      inputDoneCallBack: (String content) {
        if (content.isEmpty) return;
        debugPrint('输入了:$content');
        dynamicContent = content;
      },
    );
  }

  sendCirclData() async {
    if (dynamicContent.isEmpty) {
      return EasyLoading.showToast('请输入内容');
    }
    if (imgUrlList.isEmpty) {
      return EasyLoading.showToast('至少上传一张图片');
    }
    debugPrint('发布动态');
    var result = await RequestManager()
        .post(API.sendDynamicSetup1, params: {'content': dynamicContent});
    if (result != null && result['code'] == 0) {
      Map data = result['data'];
      String dynamicId = data['dynamic_id'].toString();
      debugPrint('发布动态1获取id:$dynamicId');
      if (dynamicId.isNotEmpty) {
        Map params = {'images': imgUrlList.join(','), 'dynamic_id': dynamicId};
        debugPrint('发布动态2params:$params');
        var result2 =
            await RequestManager().post(API.sendDynamicSetup2, params: params);
        debugPrint('发布动态2result:$result2');
        if (result2 != null && result2['code'] == 0) {
          EasyLoading.showToast(result2['message']);
          Get.back();
        }

        ///uploads/20231120/DQDJYlmNvqPY.png,
      }
    }
    // if (imgUrlList.isNotEmpty) {
    //   params['imgUrl'] = imgUrlList.join(',');
    // }
    // var request = await RequestManager().post(API.submitReport, params: params);
    // if (request != null && request['code'] == 200) {
    //   EasyLoading.showToast(request['msg']);
    //   Get.back();
    // }
  }

  void checkPermission(BuildContext context) async {
    Permission permission = Permission.storage;
    PermissionStatus status = await permission.status;
    if (status.isGranted) {
      openPicker();
    } else if (status.isDenied) {
      //权限拒绝， 需要区分IOS和Android，二者不一样
      requestPermission(permission, context);
    } else if (status.isPermanentlyDenied || status.isRestricted) {
      //权限永久拒绝，且不在提示，需要进入设置界面，IOS和Android不同
      showDialog<String>(
        context: context,
        builder: (BuildContext context) => AlertDialog(
          title: const Text('你已关闭手机相册相册权限'),
          content: const Text('请到手机设置开启相册权限'),
          actions: <Widget>[
            // if user deny again, we do nothing
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('不开启'),
            ),

            // if user is agree, you can redirect him to the app parameters :)
            TextButton(
              onPressed: () {
                Navigator.pop(context);
                openAppSettings();
              },
              child: const Text('去开启'),
            ),
          ],
        ),
      );
    } else {
      //第一次申请
      requestPermission(permission, context);
    }
  }

  void requestPermission(Permission permission, BuildContext context) async {
    //发起权限申请
    PermissionStatus status = await permission.request();
    // 返回权限申请的状态 status
    if (status.isPermanentlyDenied) {
      //权限永久拒绝，且不在提示，需要进入设置界面，IOS和Android不同
      showDialog<String>(
        context: context,
        builder: (BuildContext context) => AlertDialog(
          title: const Text('你已关闭手机相册相册权限'),
          content: const Text('请到手机设置开启相册权限'),
          actions: <Widget>[
            // if user deny again, we do nothing
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('不开启'),
            ),

            // if user is agree, you can redirect him to the app parameters :)
            TextButton(
              onPressed: () {
                Navigator.pop(context);
                openAppSettings();
              },
              child: const Text('去开启'),
            ),
          ],
        ),
      );
    }
  }

  void openPicker() async {
    AssetPickerConfig config = AssetPickerConfig(
        maxAssets: 9 - imageFiles.length, requestType: RequestType.image);

    final List<AssetEntity>? entitys =
        await AssetPicker.pickAssets(context, pickerConfig: config);
    // final List<AssetEntity>? entitys = await AssetPicker.pickAssets(context)
    if (entitys == null) return;
    //遍历
    for (var entity in entitys) {
      File? imgFile = await entity.file;
      if (imgFile != null) {
        String result = await UploadOss.upload(imgFile, fileType: 'png');
        if (result.isNotEmpty) {
          setState(() {
            imageFiles.add(imgFile);
            _imageList = PictureUtils.getImageBean(imageFiles);
            imgUrlList.add(result);
          });
          debugPrint('图片上传结果:$result');
        }
      }
    }
  }
}

class ImageBean extends DragBean {
  ImageBean({
    this.originPath,
    this.middlePath,
    this.thumbPath,
    this.originalWidth,
    this.originalHeight,
  });

  /// origin picture file path.
  String? originPath;

  /// middle picture file path.
  String? middlePath;

  /// thumb picture file path.
  /// It is recommended to use a thumbnail picture，because the original picture is too large,
  /// it may cause repeated loading and cause flashing.
  String? thumbPath;

  /// original image width.
  int? originalWidth;

  /// original image height.
  int? originalHeight;
}

class PictureUtils {
  static Future<T?> pushPage<T extends Object>(
      BuildContext context, Widget page) {
    return Navigator.push(
      context,
      CupertinoPageRoute(builder: (ctx) => page),
    );
  }

  static void showSnackBar(BuildContext context, String msg) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(msg),
        duration: const Duration(seconds: 2),
      ),
    );
  }

  static Widget getWidget(String url) {
    // 加载网络图片
    if (url.startsWith('/wxapp')) {
      return CachedNetworkImage(imageUrl: SpUtil.getImageUrl(url));
    }
    // 加载资源文件
    if (url.startsWith('assets/images')) {
      return Image.asset(url, fit: BoxFit.cover);
    }
    if (url.startsWith('/storage/emulated')) {
      return Image.file(File(url), fit: BoxFit.cover);
    }
    // 加载失败图片
    return Image.asset(ImagePath.assetsImagesHeaderForMan, fit: BoxFit.cover);
  }

  static List<ImageBean> getImageBean(List<File> files) {
    List<ImageBean> list = [];
    for (int i = 0; i < files.length; i++) {
      String url = files[i].path;
      list.add(ImageBean(
        originPath: url,
        middlePath: url,
        thumbPath: url,
        originalWidth: i == 0 ? 264 : null,
        originalHeight: i == 0 ? 258 : null,
      ));
    }
    return list;
  }
}
